#!/usr/bin/env groovy
@Library('CI_Script')
import com.yidao.www.*;

def java = [
    [
        'name' : 'd200cbs',
        'branch' : 'dev',
        'language' : 'java',
        'webhookUrl' : ''
    ]
]
def robot = [
    [
        'name' : 'D200',
        'arch' : 'x86_64',
        'branch' : 'dev',
        'distro' : '16.04'
    ],
    [
        'name' : 'D200',
        'arch' : 'aarch64',
        'branch' : 'dev',
        'distro' : '16.04'
    ]
]


def builds = [:]
def build = new build()
def base = new base()
def robotBuild = new robotBuild()
def downloads = []
def clean = params.CLEAN //布尔值参数，是否全量编译
def number = BUILD_NUMBER //Jenkins 内置变量 Build_number
def robotName = params.ROBOTNAME //机器人代号 e.g. D200
def version = params.VERSION //机器人阶段号 e.g. tr1,tr2,tr3
def robotDeployProfile = robotDeployProfile(robotName, number, version)
def remoteDir = robotDeployProfile.artifactory
def robotPackage = robotDeployProfile.packageName
def localDir = robotDeployProfile.localDir
def localPackage = robotDeployProfile.localPackage
def config = robotDeployProfile.config
def branch

for(i=0;i<java.size();i++){
    def project = java[i]
    builds["${project.name}"] = {
        def result = build.javaManuallyBuild(project.name, project.branch, project.language, project.webhookUrl)
        downloads.add(result)
    }
}

for(i=0;i<robot.size();i++){
    def project = robot[i]
    builds["${project.name}-${project.arch}-${project.distro}"] = {
        def result = robotBuild.robotAutoBuild(project.name, project.arch, project.branch, project.distro, clean)
        downloads.add(result)
        branch = project.branch
    }
}

timestamps{
    parallel builds
    println downloads
    def server = Artifactory.server 'jfrog-artifactory'
    def downloadUrl

    node('zip'){
        for(download in downloads){
            print download
            downloadUrl = download
            print downloadUrl
            base.fileDownload(downloadUrl, localDir)
        }
        def json = base.generateConfigJson(robotName, number, version)
        def jsonObj = base.readJson(json)
        def steps = jsonObj.steps
        /*
        只有 beta 版本有 tail
        */
        steps.each{
            if(branch != 'dev-beta' && it.device == 'tail'){
                steps.remove(it)
            }
        }
        def jsonStr = base.map2JsonStr(jsonObj)
        base.writeFile(jsonStr, config)
        print jsonStr
        sh 'ls -al'
        sh "zip ${robotPackage} ${localPackage}"
        def deployTarget = base.backupFolder(artifactory, robot, branch)
        base.fileUpload(robotPackage, deployTarget)

        cleanWs() //清除工作空间
    }
}